package com.solution.framework.controller;

import com.solution.framework.model.BaseBean;
import com.solution.framework.util.MessageDto;
import com.solution.framework.util.TreeModel;
import com.solution.framework.util.TreeUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Busline: sunguangzhu
 * Date: 13-7-6
 * Time: 下午12:23
 * To change this template use File | Settings | File Templates.
 */
@Controller
public abstract class BaseController<T extends BaseBean> {
    protected void writeToClient(HttpServletResponse response, String jsonStr) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().write(jsonStr);
    }

    protected void writeExceptionJsonToClient(HttpServletResponse response, String jsonStr) {
        response.setContentType("text/html; charset=utf-8");
        try {
            response.getWriter().write(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void setMessageDto(MessageDto messageDto, String message) {
        messageDto.setMessage(message);
    }

    protected String transforIds(HttpServletResponse response, Serializable ids) throws IOException {
        MessageDto messageDto = new MessageDto();
        if (ids == null || StringUtils.isBlank(ids.toString())) {
            messageDto.setSuccess(false);
            messageDto.setMessage("数据错误");
            writeToClient(response, messageDto.toString());
        }

        StringBuilder stringBuilder = new StringBuilder("");
        String[] strings = ids.toString().split(",");
        for (String string : strings) {
            stringBuilder.append("'" + string + "'");
            stringBuilder.append(",");
        }
        stringBuilder.setLength(stringBuilder.length() - 1);
        return stringBuilder.toString();
    }

    public void setTreeRoot(Model model, String name) {
        TreeModel treeRoot = TreeUtils.getTreeRoot(name);
        model.addAttribute("treeRoot", treeRoot);
    }
    protected  List<Criterion> getSearchCriterions(HttpServletRequest request){
        return new ArrayList<Criterion>();
    }

    protected String getBasePath(HttpServletRequest request){
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        return basePath;
    }
}
